package com.qf.item1.interceptor;

import com.qf.item1.entity.Customer;
import com.qf.item1.service.CustomerService;
import com.qf.item1.utils.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author 刘欣
 * @createTime 2023/2/2 17:16
 * @description 免登入
 */
@Slf4j
public class AutoLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private CustomerService customerService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("请求进入拦截器，url={}", request.getRequestURI());
        //验证是否登入
        HttpSession session = request.getSession();
        Object customerSession = session.getAttribute(Constant.CUSTOMER_SESSION_KEY);
        if (customerSession != null) {
            log.debug("用户已登入，重定向到/view/index.html");
            response.sendRedirect("/view/index.html");
            return false;
        }
        //验证勾选免登入
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(Constant.CUSTOMER_COOKIE_KEY)) {
                    final String cookieValue = cookie.getValue();
                    final String[] split = cookieValue.split("-");
                    final String username = split[0];
                    final String password = split[1];
                    final Customer customerdb = customerService.getCustomer(username, password);
                    if (customerdb != null) {
                        // 免登录校验通过,再session中设置登录状态，重定向到 /plateform.html
                        session.setAttribute(Constant.CUSTOMER_SESSION_KEY, customerdb);
                        response.sendRedirect("/view/index.html");
                        log.debug("浏览器携带免登录cookie（usertoken）,并且校验通过了，重定向到 /plateform.html");
                        return false;
                    }
                }
            }
            log.debug("浏览器没有携带免登录cookie（usertoken），直接打开登录页 /login.html");
            return true;
        } else { // 如果浏览器没有携带任何cookie，直接打开 /login.html
            log.debug("浏览器没有携带任何cookie，直接打开登录页 /login.html");
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
